package controller;

import domain.Syslog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import service.ISysLogService;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author Freedy
 * @date 2020/12/27 10:59
 */
@Component
@Aspect
public class LogAop {

    @Autowired
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    private HttpServletRequest request;
    @Autowired
    private ISysLogService sysLogService;

    private Date visitTime;
    private Class clazz;
    private Method method;

    /**
     * 前置通知
     */
    @Before("execution(* controller.*.*(..))")
    public void doBefore(JoinPoint joinPoint) throws NoSuchMethodException {
        visitTime = new Date();
        clazz = joinPoint.getTarget().getClass();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            method = clazz.getMethod(methodName);
        } else {
            Class[] classArgs = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                classArgs[i] = args[i].getClass();
            }
            method = clazz.getMethod(methodName, classArgs);
        }
    }

    /**
     * 后置通知
     */
    @After("execution(* controller.*.*(..))")
    public void doAfter() throws Exception {
        long time = System.currentTimeMillis() - visitTime.getTime();
        String url = null;
        //获取url
        if (clazz != null && method != null && clazz != LogAop.class) {
            //获取注解上的@RequestMapping("/xxx")
            RequestMapping classAnnotation = (RequestMapping)clazz.getAnnotation(RequestMapping.class);
            if (classAnnotation!=null){
                //获取类上的value
                String[] classValue = classAnnotation.value();
                //获取方法上的
                RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
                if (methodAnnotation!=null){
                    String[] methodValue = methodAnnotation.value();

                    url=classValue[0]+methodValue[0];
                }

            }
        }
        //获取访问ip地址
        String ip=request.getRemoteAddr();

        //获取用户
        SecurityContext context = SecurityContextHolder.getContext();
        User user = (User)context.getAuthentication().getPrincipal();
        String username = user.getUsername();

        //将日志相关信息封装到syslog中
        Syslog syslog = new Syslog();
        syslog.setExecutionTime(time);
        syslog.setUrl(url);
        syslog.setUsername(username);
        syslog.setVisitTime(visitTime);
        syslog.setIp(ip);
        syslog.setMethod("[类名]"+clazz.getName()+"[方法名]"+method.getName());

        sysLogService.save(syslog);
    }

}
